package cn.com.thingo.hyintelligent.ui.fragment.control;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.th.opensdk.openapi.AirConditionInfo;
import com.th.opensdk.openapi.CurtainInfo;
import com.th.opensdk.openapi.DimmerInfo;
import com.th.opensdk.openapi.RemoterInfo;
import com.th.opensdk.openapi.SceneGroupInfo;
import com.th.opensdk.openapi.SceneInfo;
import com.th.opensdk.openapi.SwitchInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.App;
import cn.com.thingo.hyintelligent.base.RootFragment;
import cn.com.thingo.hyintelligent.base.contract.ControlItemContract;
import cn.com.thingo.hyintelligent.model.bean.DoorLockAuthBean;
import cn.com.thingo.hyintelligent.presenter.ControlItemPresenter;
import cn.com.thingo.hyintelligent.ui.adapter.DeviceListAdapter;
import cn.com.thingo.hyintelligent.util.SPUtils;
import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.widget.ITabView;
import q.rorbin.verticaltablayout.widget.QTabView;
import q.rorbin.verticaltablayout.widget.TabView;

/**
 */
public class ControlItemFragment extends RootFragment<ControlItemPresenter> implements ControlItemContract.View, VerticalTabLayout.OnTabSelectedListener {
    @BindView(R.id.control_device_type_list)
    VerticalTabLayout tabDevice;
    @BindView(R.id.control_device_list)
    RecyclerView rvDeviceList;
    private THOpenSDK thOpenSDK;
    private DeviceListAdapter adapter;
    //灯光数据 调光组
    private List<DimmerInfo> dimmerInfoList = new ArrayList<>();
    //灯光数据 开关组
    private List<SwitchInfo> switchInfoList = new ArrayList<>();
    //飘移窗数据
    private List<SceneInfo> sceneInfoList = new ArrayList<>();
    //窗帘数据
    private List<CurtainInfo> curtainInfoList = new ArrayList<>();
    //空调数据
    private List<RemoterInfo> airConditionList = new ArrayList<>();
    private List<AirConditionInfo> airConditionInfos = new ArrayList<>();
    //电视数据
    private List<RemoterInfo> televisionList = new ArrayList<>();
    //门锁数据
    private List<RemoterInfo> doorLockList = new ArrayList<>();
    //音乐数据
    private List<RemoterInfo> musicList = new ArrayList<>();
    //设备组
    private List<Integer> deviceList = new ArrayList<>();


    private int currentRoomId;

    public ControlItemFragment() {
        // Required empty public constructor
    }

    public static ControlItemFragment newInstance(int roomId) {
        ControlItemFragment fragment = new ControlItemFragment();
        Bundle args = new Bundle();
        args.putInt("room_id", roomId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();

    }

    public void initData() {
        if (deviceList.size() > 0) {
            cleanDevice();
        }
        if (thOpenSDK == null) {
            thOpenSDK = THOpenSDK.getInstance();
        }
        initDevice();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            currentRoomId = getArguments().getInt("room_id");
        }
        thOpenSDK = THOpenSDK.getInstance();
        initView(view);
    }


    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void cleanDevice() {
        tabDevice.removeAllTabs();
        deviceList.clear();
        dimmerInfoList.clear();
        switchInfoList.clear();
        sceneInfoList.clear();
        curtainInfoList.clear();
        airConditionList.clear();
        airConditionInfos.clear();
        televisionList.clear();
        doorLockList.clear();
        musicList.clear();

    }

    private void initView(View view) {
        if (rvDeviceList == null) {
            rvDeviceList = view.findViewById(R.id.control_device_list);
        }
        rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new DeviceListAdapter(mContext, dimmerInfoList, switchInfoList, sceneInfoList,
                curtainInfoList, airConditionList,airConditionInfos, televisionList, doorLockList, musicList, deviceList);
        rvDeviceList.setAdapter(adapter);
        //todo 左边改成recyclerview 后续做
//        rvDeviceListener();
        tabDevice.setTabMode(VerticalTabLayout.TAB_MODE_SCROLLABLE);
        tabDevice.setTabHeight(100);
        tabDevice.setTabMargin(10);
        tabDevice.addOnTabSelectedListener(this);
    }

    private void rvDeviceListener() {
        rvDeviceList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int position = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                tabDevice.setTabSelected(position);
            }
        });
    }

    private void initDevice() {
        initLite();
        initWindow();
        initCurtain();
        initRemoter();
        adapter.notifyDataSetChanged();
    }


    private void initRemoter() {
        List<RemoterInfo> remoterList = thOpenSDK.getRemoterList();
        initAirCondition(remoterList);
//        initTelevision(remoterList);
        initDoorLock(remoterList);
        initMusic(remoterList);
    }

    //初始化门锁
    private void initDoorLock(List<RemoterInfo> remoterList) {
        boolean doorLockFlag = false;//判断当前房间是否有门锁
        if (TextUtils.equals(SPUtils.newInstance().getString(SPUtils.GATEWAY_IS_CREATE), "1")) {
            //假如网关是自己创建的
            if (remoterList != null && remoterList.size() > 0) {
                for (int i = 0; i < remoterList.size(); i++) {
                    int roomId = remoterList.get(i).getRoomId();
                    int controlType = remoterList.get(i).getRemoterType();
                    if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_LOCKER) {
                        doorLockFlag = true;
                        doorLockList.add(remoterList.get(i));
                    }
                }
            }
            if (doorLockFlag) {
                deviceList.add(DeviceListAdapter.DEVICE_TYPE_DOOR_LOCK);
                tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("门锁").setTextSize(16)
                        .setTextColor(0xFF333333, 0xFF999999).build()));
            }
        } else {
            mPresenter.getDoorLockAuthList(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN), App.getDataBean().getId(), remoterList);
        }
    }

    //初始化电视
    private void initTelevision(List<RemoterInfo> remoterList) {
        boolean televisionFlag = false;//判断当前房间是否有空调
        if (remoterList != null && remoterList.size() > 0) {
            for (int i = 0; i < remoterList.size(); i++) {
                int roomId = remoterList.get(i).getRoomId();
                int controlType = remoterList.get(i).getControlType();
                if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_TV) {
                    televisionFlag = true;
                    televisionList.add(remoterList.get(i));
                }
            }
        }
        if (televisionFlag) {
            deviceList.add(DeviceListAdapter.DEVICE_TYPE_TELEVISION);
            tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("电视").setTextSize(16)
                    .setTextColor(0xFF333333, 0xFF999999).build()));
        }
    }

    //初始化空调
    private void initAirCondition(List<RemoterInfo> remoterList) {
        boolean airConditionFlag = false;//判断当前房间是否有空调
        if (remoterList != null && remoterList.size() > 0) {
            for (int i = 0; i < remoterList.size(); i++) {
                int roomId = remoterList.get(i).getRoomId();
                int remoterType = remoterList.get(i).getRemoterType();
                if (roomId == currentRoomId && remoterType == RemoterInfo.HOME_REMOTER_TYPE_AIR_CONDITION) {
                    airConditionFlag = true;
                    airConditionList.add(remoterList.get(i));
                }
            }
        }
        List<AirConditionInfo> airConditions = thOpenSDK.getAirConditionList();
        if (airConditions != null && airConditions.size() > 0) {
            for (int i = 0; i < airConditions.size(); i++) {
                if (currentRoomId == airConditions.get(i).getRoomId()) {
                    airConditionFlag = true;
                    airConditionInfos.add(airConditions.get(i));
                }
            }
        }
        if (airConditionFlag) {
            deviceList.add(DeviceListAdapter.DEVICE_TYPE_AIR_CONDITION);
            tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("空调").setTextSize(16)
                    .setTextColor(0xFF333333, 0xFF999999).build()));
        }

    }

    //初始化窗帘
    private void initCurtain() {
        if (thOpenSDK != null) {
            List<CurtainInfo> curtainList = thOpenSDK.getCurtainList();//窗帘列表
            boolean curtainFlag = false;//判断当前房间是否有窗帘
            if (curtainList != null && curtainList.size() > 0) {
                for (int i = 0; i < curtainList.size(); i++) {
                    int roomId = curtainList.get(i).getRoomId();
                    if (roomId == currentRoomId) {
                        curtainFlag = true;
                        curtainInfoList.add(curtainList.get(i));
                    }
                }
            }
            if (curtainFlag) {
                deviceList.add(DeviceListAdapter.DEVICE_TYPE_CURTAIN);
                tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("窗帘").setTextSize(16)
                        .setTextColor(0xFF333333, 0xFF999999).build()));
            }
        }
    }

    //初始化飘移窗
    private void initWindow() {
        if (thOpenSDK != null) {
            List<SceneInfo> sceneInfoList = new ArrayList<>();
            List<SceneGroupInfo> sceneGroupList = THOpenSDK.getInstance().getSceneGroupList();//场景列表 窗户暂时依托场景
            for (int i = 0; i < sceneGroupList.size(); i++) {
                List<SceneInfo> sceneList = sceneGroupList.get(i).getSceneList();
                if (sceneList.size() > 0) {
                    sceneInfoList.addAll(sceneList);
                }
            }
            boolean windowFlag = false;
            if (sceneInfoList.size() > 0) {
                for (int i = 0; i < sceneInfoList.size(); i++) {
                    int roomId = sceneInfoList.get(i).getRoomId();
                    if (roomId == currentRoomId && sceneInfoList.get(i).getSceneName().startsWith("窗户-")) {
                        windowFlag = true;
                        this.sceneInfoList.add(sceneInfoList.get(i));
                    }
                }
            }
            if (windowFlag) {
                deviceList.add(DeviceListAdapter.DEVICE_TYPE_WINDOW);
                tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("飘移窗").setTextSize(16)
                        .setTextColor(0xFF333333, 0xFF999999).build()));
            }
        }
    }

    //初始化灯光
    private void initLite() {
        if (thOpenSDK != null) {
            List<DimmerInfo> dimmerList = thOpenSDK.getDimmerList();//调光列表
            List<SwitchInfo> switchList = thOpenSDK.getSwitchList();//开关列表
            boolean liteFlag = false;//判断当前房间是否有灯光
            if (dimmerList != null && dimmerList.size() > 0) {
                for (int i = 0; i < dimmerList.size(); i++) {
                    int roomId = dimmerList.get(i).getRoomId();
                    if (roomId == currentRoomId) {
                        liteFlag = true;
                        dimmerInfoList.add(dimmerList.get(i));
                    }
                }
            }
            if (switchList != null && switchList.size() > 0) {
                for (int i = 0; i < switchList.size(); i++) {
                    int roomId = switchList.get(i).getRoomId();
                    if (roomId == currentRoomId) {
                        liteFlag = true;
                        switchInfoList.add(switchList.get(i));

                    }
                }
            }
            if (liteFlag) {
                deviceList.add(DeviceListAdapter.DEVICE_TYPE_LITE);
                tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("灯光").setTextSize(16)
                        .setTextColor(0xFF333333, 0xFF999999).build()));
            }
        }
    }

    private void initMusic(List<RemoterInfo> remoterList) {
        boolean musicFlag = false;//判断当前房间是否有音乐
        if (remoterList != null && remoterList.size() > 0) {
            for (int i = 0; i < remoterList.size(); i++) {
                int roomId = remoterList.get(i).getRoomId();
                int controlType = remoterList.get(i).getRemoterType();
                if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_MUSIC) {
                    musicFlag = true;
                    musicList.add(remoterList.get(i));
                }
            }
        }
        if (musicFlag) {
            deviceList.add(DeviceListAdapter.DEVICE_TYPE_MUSIC);
            tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("音乐").setTextSize(16)
                    .setTextColor(0xFF333333, 0xFF999999).build()));
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_control_item;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }


    @Override
    public void onTabSelected(TabView tab, int position) {
        rvDeviceList.scrollToPosition(position);
    }

    @Override
    public void onTabReselected(TabView tab, int position) {

    }

    @Override
    public void viewDoorLockAuthList(DoorLockAuthBean doorLockAuthBean, List<RemoterInfo> remoterList) {
        boolean isAuth = false;
        String username = SPUtils.newInstance().getString(SPUtils.LOGIN_USERNAME);
        List<DoorLockAuthBean.DataBean> data = doorLockAuthBean.getData();
        for (int i = 0; i < data.size(); i++) {
            if (TextUtils.equals(data.get(i).getTelephone(), username)) {
                isAuth = true;
                break;
            }
        }
        if (isAuth) {
            boolean doorLockFlag = false;
            if (remoterList != null && remoterList.size() > 0) {
                for (int i = 0; i < remoterList.size(); i++) {
                    int roomId = remoterList.get(i).getRoomId();
                    int controlType = remoterList.get(i).getRemoterType();
                    if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_LOCKER) {
                        doorLockFlag = true;
                        doorLockList.add(remoterList.get(i));
                    }
                }
            }
            if (doorLockFlag) {
                deviceList.add(DeviceListAdapter.DEVICE_TYPE_DOOR_LOCK);
                tabDevice.addTab(new QTabView(mContext).setTitle(new ITabView.TabTitle.Builder().setContent("门锁").setTextSize(16)
                        .setTextColor(0xFF333333, 0xFF999999).build()));
                adapter.notifyDataSetChanged();
            }
        }
    }
}
